import tokenCache from '@/request/token/tokenCache'
import loginHandler from '@/utils/loginHandler'
const { atob } = require('abab')

export default {
  get: function() {
    let token = tokenCache.get()
    if (token !== '') {
      return new Promise((resolve, reject) => {
        resolve(token)
      })
    } else {
      /* return new Promise((resolve, reject) => {
        loginHandler.login().then(result => {
          // 平台token
          this.refreshDhccToken(result.dhccamToken)
          // 安全token
          this.refreshAuthToken(result.authToken)
          resolve(tokenCache.get())
        }).catch(err => {
          reject(err)
        })
      }) */
	  uni.showModal({
	  	title: '提示',
	  	content: '登陆已过期，请重新登录',
	  	showCancel:false,
	  	confirmColor: '#0566A8',
	  	confirmText:'去登陆',
	  	success: function(res) {
	  		if (res.confirm) {
	  			uni.navigateTo({
	  				url:'/pages/loginPage/loginPage'
	  			})
	  		}
	  	},
	  	fail: function(res) {
	  	
	  	}
	  })
    }
  },
  remove: function() {
    tokenCache.remove()
  },
  refreshAuthToken: function(authToken) {
    let tokenArray = authToken.split('.')
    let tokenParam = JSON.parse(atob(tokenArray[1]))
    let remain_time = tokenParam.exp - tokenParam.iat
    tokenCache.set(true, authToken, remain_time)
  },
  refreshDhccToken: function(dhccamToken) {
	  if (dhccamToken.remain_time === 0) {
	    tokenCache.set(false, dhccamToken.access_token)
	  } else {
	    tokenCache.set(false, dhccamToken.access_token, dhccamToken.remain_time)
	  }
  }
}
